from rqalpha.api import *
from rqalpha.utils.logger import user_log, system_log
import numpy as np
import unittest
from rqalpha.model.order import Order

'''
ma5>ma20 做多，否则做空
测试用例：测试撤单功能是否正常
'''

static_param = {"future_vol": 1, "stock_amount": 200000, "stock_shares": 200, "stock_lots": 5, "slippage": 3, "unit": 0.01}
dynamic_param = {"main_contract": None,
                 "last_main_contract": None, "is_switch": False}


def init(context):
    """context内引入全局变量s1，存储目标合约信息
    :param context:
    :return:
    """
    user_log.info("init")
    context.stock_symbol = '600489.SH'
    subscribe(context.stock_symbol)
    subscribe_event(EVENT.TRADE, handle_trader)
    context.trade_list = []
    context.position = 0 # 初始仓位为0


def before_trading(context):
    pass


def handle_bar(context, bar_dict):
    """
     先判断当前有没有订单，有就撤单，没有，不执行撤单
    :param context: 策略上下文
    :param bar_dict: 当前合约池内所有合约的bar数据信息都会更新在bar_dict里面
    :return:
    """
    bar_datetime = bar_dict.dt

    open_orders = get_open_orders()
    if len(open_orders) > 0:
        for o in open_orders:
            cancel_order(o)

    close: np.ndarray = history_bars(context.stock_symbol, 20, "1m", ['close'], adjust_type="none")
    if len(close) < 20:
        return
    if close[-5:].mean() > close.mean():
        buy_stock(context, bar_dict[context.stock_symbol].close * 0.8)
    else:
        sell_stock(context, bar_dict[context.stock_symbol].close * 0.8)


def buy_stock(context, price):
    """
    :param context:策略上下文
    :param price: 价格
    :return: null
    """
    qty = context.portfolio.positions[context.stock_symbol].quantity
    if qty <= 0:
        buy_order_3 = order_lots(context.stock_symbol, static_param["stock_lots"], style=LimitOrder(price))
        user_log.info("指定手数开仓={}".format(buy_order_3))


def sell_stock(context, price):
    """
    :param context: 策略上下文
    :param price: 价格
    :return:
    """
    qty = context.portfolio.positions[context.stock_symbol].sellable
    if qty > 0:
        sell_order_3 = order_lots(context.stock_symbol, -static_param["stock_lots"], style=LimitOrder(price))
        user_log.info("指定手数平仓={}".format(sell_order_3))


def handle_trader(context, trader):
    """
    收到成交信息，将其添加到list中
    :param context: 策略上下文
    :param trader:交易
    :return:
    """
    context.trade_list.append(trader)
    user_log.info("成交信息={}".format(trader.trade))
    if(trader.trade.side == SIDE.BUY):
        context.position = context.position + trader.trade.last_quantity
    else:
        context.position = context.position - trader.trade.last_quantity
    actual_position = context.portfolio.positions[context.stock_symbol].quantity
    print("预期持仓：", context.position, "，实际持仓：", actual_position)

